package com.jt.www.job.issue;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.jt.www.common.service.JobQueryListService;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.pay.ResBindQo;
import com.jt.www.model.pol.FileInfoVO;
import com.jt.www.model.pol.UploadEndorsementCheckFile;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.remote.DexClient;
import com.jt.www.remote.PolClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description: 绑定资源
 * <p>
 * 未处理/电子批单处理失败/重新绑定次数小于6次
 * 如果有资源ID直接去绑定/没有资源ID  去调用数据交换中心去下再上传，并且绑定
 * 1.根据状态和重试次数，查询电子批单的信息
 * 2.如果有资源ID直接去绑定，重试次数+1
 * 3.如果没有资源ID ，重试次数+1， 去调用数据交换中心去下再上传，并且绑定
 * @author: xuxinku
 * @Date: 2019/11/22 14:01
 * @ModifiedDate：
 * @Copyright:江泰保险股份有限公司
 */

@Component
@EnableScheduling
public class CheckPdBindResourceTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckPdBindResourceTask.class);
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long ENDOR_TIME_OUT = 30L;
    /**
     * 电子批单是否绑定的定时任务 缓存key
     */
    private static final String ENDOR_LOCK_KEY = "EDU_ENDOR_ISSUE";
    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    JobQueryListService jobQueryListService;
    @Autowired
    DexClient dexClient;
    @Autowired
    PolClient polClient;
    /**
     * 任务开关
     */

    @Value("${jtpf.endor.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */

    @Value("${jtpf.endor.cron}")
    private String cron;// 每隔一分钟执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        if (RedisUtil.setLock(ENDOR_LOCK_KEY, "1", ENDOR_TIME_OUT)) {
            Runnable task0 = () -> checkStart();
            Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
            taskRegistrar.addTriggerTask(task0, trigger0);
        }
    }

    private void checkStart() {
        String currentTime = DateUtils.getCurrentTime();
        log.info(currentTime + "CheckPdBindResourceTask satrt,检查出单电子批单绑定资源的的任务开始...");
        Weekend<IssuePolicyLogEntity> weekend = Weekend.of(IssuePolicyLogEntity.class);
        WeekendCriteria<IssuePolicyLogEntity, Object> criteria = weekend.weekendCriteria();
//        criteria.andEqualTo(IssuePolicyLogEntity::getStatus, "3");
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("3");
        criteria.andIn(IssuePolicyLogEntity::getStatus, statusList);
        criteria.andLessThan(IssuePolicyLogEntity::getTimes, 6);
        criteria.andEqualTo(IssuePolicyLogEntity::getType, "2");
        List<IssuePolicyLogEntity> resultList = jobQueryListService.getJobProcessIssuePolicyLogList(weekend);
        if (resultList != null && resultList.size() > 0) {
            for (IssuePolicyLogEntity t : resultList) {
                String ifCode = t.getIfCode();
                switch (ifCode) {
                    case "20190516012":
                        //山东临沂产品
                        handleSD(t);
                        break;
                    default:
                        log.error("{}错误的批单ifCode:{}", currentTime, ifCode);
                }
            }
        }
        log.info(currentTime + "CheckPdBindResourceTask end,检查出单电子批单绑定资源的的任务结束...");
    }


    /**
     * 山东电子批单
     *
     * @param t
     */

    private void handleSD(IssuePolicyLogEntity t) {

        String param = t.getParam();
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;

        try {
            if (StringUtils.isEmpty(ePolicyId)) {
                // 文件id为空  继续下载
                log.info(DateUtils.getCurrentTime() + "山东临沂电子批单的job,入参：" + param);
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, param);
                log.info(DateUtils.getCurrentTime() + "山东临沂电子批单的job,回参：" + responseEntity.getBody() + "," + responseEntity.getStatusCodeValue());
                // 请求200，继续执行
                if (responseEntity.getStatusCodeValue() != 200) {
                    log.error("请求下载临沂电子批单失败");
                    t.setTimes(times);
                    t.setEPolicyId(ePolicyId);
                    t.setStatus("3");
                    issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
                } else {
                    String fileId = responseEntity.getBody();
                    t.setEPolicyId(fileId);
                    bindresource(t);
                }
            } else {
                bindresource(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(DateUtils.getCurrentTime() + ",job请求下载临沂电子批单失败，批单申请号：" + t.getApplicationFormCode());
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }


    }


    private void bindresource(IssuePolicyLogEntity t) {
        ResBindQo resBindQo = null;
        String ePolicyId = t.getEPolicyId();
        int times = t.getTimes() + 1;
        // 继续去绑定资源
        //拼接绑定资源入参
        UploadEndorsementCheckFile uploadEndorsementCheckFile = new UploadEndorsementCheckFile();
        uploadEndorsementCheckFile.setApplyNo(t.getApplicationFormCode());
        uploadEndorsementCheckFile.setEndorseStatus("03");
        ArrayList<FileInfoVO> fileInfoVOS = new ArrayList<>();
        FileInfoVO fileInfoVO = new FileInfoVO();
        fileInfoVO.setFileName(t.getApplicationFormCode());
        fileInfoVO.setFileType("05");
        fileInfoVO.setFileUrl(ePolicyId);
        fileInfoVOS.add(fileInfoVO);
        uploadEndorsementCheckFile.setFileInfoVO(fileInfoVOS);

        //调用批单中心绑定资源接口
        log.info(DateUtils.getCurrentTime() + "批单号 " + t.getApplicationFormCode() + " 调用绑定资源接口开始，入参：" + JSON.toJSON(uploadEndorsementCheckFile));
        ResponseEntity<GenericListResponse<JsonObject>> genericListResponseResponseEntity = null;
        //log.info(DateUtils.getCurrentTime() + "批单号 " + t.getApplicationFormCode()  + " 调用绑定资源接口返回结果码" + code + ":" + body.getMsg());

        try {
            genericListResponseResponseEntity = polClient.uploadEndorsementCheckFiles(uploadEndorsementCheckFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调用绑定资源接口出错!{}", e);
        }
        String code;
        //出错时，超时时处理
        if (null == genericListResponseResponseEntity) {
            code = "9999";
        } else {
            GenericListResponse<JsonObject> body = genericListResponseResponseEntity.getBody();
            code = body.getCode();
            log.info(DateUtils.getCurrentTime() + "调用绑定资源接口返回结果码" + code + ":" + body.getMsg());
        }
        if (!"0000".equals(code)) {
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("3");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        } else {
            t.setTimes(times);
            t.setEPolicyId(ePolicyId);
            t.setStatus("2");
            issuePolicyLogEntityMapper.updateByPrimaryKeySelective(t);
        }
    }

}
